require 'View/UIBase/UIBase'

UIAchieveAward = UIBase.New(PanelNames.UIAchieveAward)

function UIAchieveAward.Init(type)
    UIAchieveAward.type = type or EnumConst.TaskType.achievementTask
    UIBase.Init(UIAchieveAward);
end

-- 创建回调
function UIAchieveAward:OnCreate()
    self.itemList = self:SetDynamicList(self:GetChild("elementGroup"),self.updateItem)
    self:addEvent();
end

-- 显示
function UIAchieveAward:OnEnable()
    self:Refresh();
end

function UIAchieveAward:addEvent()
    self:RegisterOnClick(self:GetChild("btnClose"),self.OnClose);
end

function UIAchieveAward:removeEvent()
end

function UIAchieveAward:Refresh()
    self:UpdateData();
end

function UIAchieveAward:UpdateData()
    self.tableData = logicMgr.TaskManager.getTaskBoxByType(self.type);
    table.sort(self.tableData, function (a, b) return a.f_NeedExpCount > b.f_NeedExpCount end);
    self.achieveNum = logicMgr.TaskManager.getTaskLivenessServerData(self.type)["liveness"];
    self.itemList.numItems = #self.tableData;
    self.now = 1;
    local reward;
    for k, v in pairs(self.tableData) do
        reward = logicMgr.TaskManager.getTaskLivenessBoxServerData(v.f_BoxID)["reward"];
        if reward == 0 or reward == 1 then
            self.now = k;
        end
    end
    self.itemList:ScrollToView(self.now - 1, false, false);
end

---
function UIAchieveAward:updateItem(index, itemobj)
    local info = self.tableData[index];
    local data = logicMgr.TaskManager.getTaskLivenessBoxServerData(info.f_BoxID);
    local position = itemobj:GetController("position");
    local state = itemobj:GetController("state");
    local limit = itemobj:GetChild("limit");
    local limit2 = itemobj:GetChild("limit2");
    local itemGroup = itemobj:GetChild("itemGroup");
    local btnGet = itemobj:GetChild("btnGet");
    position.selectedIndex = index % 2;
    if data["reward"] == 1 then
        state.selectedIndex = 2
    elseif self.achieveNum >= info.f_NeedExpCount then
        state.selectedIndex = 1
    else
        state.selectedIndex = 0
    end
    limit.text = info.f_NeedExpCount;
    limit2.text = info.f_NeedExpCount;
    logicMgr.CostManager.RefreshItemList(itemGroup, decodeJsonStrToTabel(info.f_BoxAward), 2);
    btnGet.onClick:Clear();
    btnGet.onClick:Add(function()
        taskInfoHandler.SendReqLivenessInfo(info.f_BoxID)
        AudioManager.Play(1010)
    end);
end

-- 关闭
function UIAchieveAward:OnClose()
    self:OnBack();
end

-- 隐藏
function UIAchieveAward:OnDisable()
end

-- 卸载
function UIAchieveAward:OnDestroy()
    self:removeEvent();
end

return UIAchieveAward